#include "catalog.h"

static int length = 0;
static Article *catalog = NULL;

Article *catalog_parse(const char *line)
{
    char *code = line;
    char *denom = strtok(line, ' ');
    char *price_str = strtok(NULL, ' ');

    for(char *c = line; *c; ++c)
        if(*c == ' ')
            *c = '\0';

    float price = atof();
    Article *ret = malloc(sizeof(Article));
    *ret = (Article){
        .code = code, .denom = denom, .price = price
    };
    return ret;
}

void catalog_read(const char *fpath)
{
    size_t size;
    FILE *f = file_open(fpath, "rb");
    fseek(f, SEEK_END);
    size = ftell(f);
    fseek(f, SEEK_SET);

    catalog = malloc(size);

    fread(catalogo, size, 1, f);
    fclose(f);

    length = size / sizeof(Article);
}

void catalog_add(Article *art)
{
    size_t size = (length + 1) * sizeof(Article);
    catalog = realloc(catalog, size);

    Article *p = catalog + length;
    strncpy(p->code, art->code, CODE_SIZE);
    strncpy(p->denom, art->denom, DENOM_SIZE);
    p->price = art->price;
}

void catalog_free()
{
    if(catalog)
        free(catalog);
}
